﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MesProjectWinform.Public.Common;
using Newtonsoft.Json.Linq;
using MesProjectWinform.BasicData.Entity;
using Newtonsoft.Json;
using System.Net.Http;
using System.Web;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraTreeList;
using DevExpress.XtraTreeList.Nodes;

namespace MesProjectWinform.BasicData.基础实现.Bom
{
    public partial class Bom : DevExpress.XtraEditors.XtraForm
    {
        // API服务端口号
        private const string ApiBaseUrl = "http://47.110.243.157:5052/";
        
        // 定义一个字典用来存储BOM是否有子集
        private Dictionary<string, bool> _bomHasChildren = new Dictionary<string, bool>();
        
        // BOM类型和阶别的映射字典，根据编码确定类型和阶别
        private Dictionary<string, Tuple<string, string>> _bomTypeRankMapping;
        
        // 右键菜单
        private ContextMenuStrip contextMenuStrip;
        private ToolStripMenuItem addChildMenuItem;
        private ToolStripMenuItem bindProductMenuItem;
        
        public Bom()
        {
            InitializeComponent();
            
            // 设置窗体居中显示
            this.StartPosition = FormStartPosition.CenterScreen;
            
            // 初始化控件
            InitializeControls();
            
            // 初始化BOM类型和阶别映射
            InitializeBomTypeRankMapping();
            
            // 加载产品项数据到下拉框
            LoadProductItems();
            
            // 初始化右键菜单
            InitializeContextMenu();
            
            // 初始化时加载数据
            LoadData();
        }
        
        /// <summary>
        /// 初始化BOM类型和阶别映射
        /// </summary>
        private void InitializeBomTypeRankMapping()
        {
            // 创建映射字典，存储编码对应的类型和阶别
            // Tuple的Item1是BOM类型，Item2是阶别
            _bomTypeRankMapping = new Dictionary<string, Tuple<string, string>>
            {
                { "", new Tuple<string, string>("", "0") },
                { "UAV001", new Tuple<string, string>("成品", "0") },
                { "UAV002", new Tuple<string, string>("半成品", "0") },
                { "UAV003", new Tuple<string, string>("原材料", "0") },
                { "UAV004", new Tuple<string, string>("半成品", "0") },
                { "UAV005", new Tuple<string, string>("成品", "0") },
                { "UAV006", new Tuple<string, string>("原材料", "0") },
                { "UAV007", new Tuple<string, string>("成品", "0") },
                { "UAV008", new Tuple<string, string>("半成品", "0") }
            };
        }
        
        /// <summary>
        /// 根据编码获取BOM类型和阶别
        /// </summary>
        /// <param name="bomCode">BOM编码</param>
        /// <returns>包含BOM类型和阶别的元组</returns>
        private Tuple<string, string> GetBomTypeAndRankByCode(string bomCode)
        {
            if (_bomTypeRankMapping.TryGetValue(bomCode, out var typeRank))
            {
                return typeRank;
            }
            
            // 默认返回成品和0阶别
            return new Tuple<string, string>("成品", "0");
        }
        
        /// <summary>
        /// 初始化右键菜单
        /// </summary>
        private void InitializeContextMenu()
        {
            try
            {
                // 创建右键菜单
                contextMenuStrip = new ContextMenuStrip();
                
                // 添加下级菜单项
                addChildMenuItem = new ToolStripMenuItem("添加下级");
                addChildMenuItem.Click += AddChildMenuItem_Click;
                contextMenuStrip.Items.Add(addChildMenuItem);
                
                // 绑定产品菜单项
                bindProductMenuItem = new ToolStripMenuItem("绑定产品");
                bindProductMenuItem.Click += BindProductMenuItem_Click;
                contextMenuStrip.Items.Add(bindProductMenuItem);
                
                // 为GridView绑定鼠标右键点击事件
                gridView1.MouseUp += GridView1_MouseUp;
                
                Console.WriteLine("右键菜单初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化右键菜单异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        /// <summary>
        /// 添加下级菜单项点击事件
        /// </summary>
        private void AddChildMenuItem_Click(object sender, EventArgs e)
        {
            // 调用添加下级方法
            AddChildBom();
        }
        
        /// <summary>
        /// 绑定产品菜单项点击事件
        /// </summary>
        private void BindProductMenuItem_Click(object sender, EventArgs e)
        {
            // 这里暂时不实现具体功能，只是一个空的点击事件
            Console.WriteLine("绑定产品菜单项被点击");
            XtraMessageBox.Show("绑定产品功能将在后续实现", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        
        /// <summary>
        /// GridView鼠标右键点击事件
        /// </summary>
        private void GridView1_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                // 只处理右键点击
                if (e.Button != MouseButtons.Right)
                    return;
                
                // 获取点击位置的行信息
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = gridView1.CalcHitInfo(e.Location);
                
                // 如果点击在行上
                if (hitInfo.InRow)
                {
                    // 获取选中行的BOM对象
                    Bommodel bomModel = gridView1.GetRow(hitInfo.RowHandle) as Bommodel;
                    if (bomModel != null)
                    {
                        // 根据条件控制菜单项的可见性
                        
                        // 1. 只有类型为半成品或成品时才能添加下级
                        bool canAddChild = bomModel.BomType == "半成品" || bomModel.BomType == "成品";
                        addChildMenuItem.Visible = canAddChild;
                        addChildMenuItem.Enabled = canAddChild;
                        
                        // 2. 只有阶别为0时才能显示绑定产品
                        int bomRank = 0;
                        if (!string.IsNullOrEmpty(bomModel.Bomranks))
                        {
                            int.TryParse(bomModel.Bomranks, out bomRank);
                        }
                        bindProductMenuItem.Visible = (bomRank == 0);
                        
                        // 设置当前选中行
                        gridView1.FocusedRowHandle = hitInfo.RowHandle;
                        
                        // 显示右键菜单
                        contextMenuStrip.Show(gridControl1, e.Location);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"显示右键菜单异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        /// <summary>
        /// 初始化控件
        /// </summary>
        private void InitializeControls()
        {
            try
            {
                // 设置编码控件为下拉框
                textEdit1.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
                
                // 添加提示标签（只能查询成品）
                Label lblFinishedProductsOnly = new Label();
                
                lblFinishedProductsOnly.AutoSize = true;
                lblFinishedProductsOnly.Location = new Point(textEdit1.Location.X, textEdit1.Location.Y - 20);
                this.Controls.Add(lblFinishedProductsOnly);
                lblFinishedProductsOnly.BringToFront();
                
                // 配置GridView基本选项
                gridView1.OptionsBehavior.Editable = false;
                gridView1.OptionsView.ShowGroupPanel = false;
                gridView1.OptionsView.ShowIndicator = true;
                
                // 设置事件处理
                gridView1.CustomDrawCell += GridView1_CustomDrawCell;
                gridView1.MouseDown += GridView1_MouseDown;
                
                // 添加双击事件处理
                gridView1.DoubleClick += GridView1_DoubleClick;
                gridView1.Tag = "DoubleClickHandlerAdded";
                
                // 添加提示信息
                Label lblDoubleClickTip = new Label();
                lblDoubleClickTip.AutoSize = true;
                lblDoubleClickTip.Text = "双击行可展开/收起子项";
                lblDoubleClickTip.Location = new Point(gridControl1.Location.X, gridControl1.Location.Y - 20);
                lblDoubleClickTip.ForeColor = Color.Blue;
                this.Controls.Add(lblDoubleClickTip);
                lblDoubleClickTip.BringToFront();
                
                Console.WriteLine("控件初始化完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"初始化控件异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        // 自定义绘制单元格事件
        private void GridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            try
            {
                if (e.Column.FieldName == "Bomcode")
                {
                    GridView view = sender as GridView;
                    Bommodel bomModel = view.GetRow(e.RowHandle) as Bommodel;
                    if (bomModel != null)
                    {
                        // 获取单元格区域
                        Rectangle rect = e.Bounds;
                        
                        // 根据层级计算缩进
                        int level = 0;
                        if (!string.IsNullOrEmpty(bomModel.Bomranks))
                        {
                            int.TryParse(bomModel.Bomranks, out level);
                        }
                        
                        // 每个层级缩进30像素，增加缩进距离
                        int indent = level * 30;
                        if (indent < 0) indent = 0;
                        
                        // 清除单元格背景
                        e.Appearance.DrawBackground(e.Cache, rect);
                        
                        // 如果有子项，绘制+/-符号
                        if (_bomHasChildren.ContainsKey(bomModel.Bomcode) && _bomHasChildren[bomModel.Bomcode])
                        {
                            // 绘制+/-符号
                            string symbol = bomModel.IsExpanded ? "-" : "+";
                            using (Font symbolFont = new Font("Arial", 10, FontStyle.Bold))
                            using (SolidBrush textBrush = new SolidBrush(Color.FromArgb(50, 50, 50)))
                            {
                                float x = rect.X + indent + 5;
                                float y = rect.Y + (rect.Height - symbolFont.Height) / 2;
                                e.Graphics.DrawString(symbol, symbolFont, textBrush, x, y);
                            }
                        }
                        
                        // 绘制文本内容
                        using (SolidBrush textBrush = new SolidBrush(e.Appearance.ForeColor))
                        {
                            float textX = rect.X + indent + 20; // 文本位置在符号之后
                            float textY = rect.Y + (rect.Height - e.Appearance.Font.Height) / 2;
                            e.Graphics.DrawString(bomModel.Bomcode, e.Appearance.Font, textBrush, textX, textY);
                        }
                        
                        // 标记为已处理
                        e.Handled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"自定义绘制单元格异常: {ex.Message}\n{ex.StackTrace}");
                // 继续默认绘制
                e.Handled = false;
            }
        }
        
        // 鼠标点击事件处理
        private void GridView1_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                // 只处理左键点击
                if (e.Button != MouseButtons.Left)
                    return;
                    
                GridView view = sender as GridView;
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = view.CalcHitInfo(e.Location);
                
                if (hitInfo.InRowCell && hitInfo.Column.FieldName == "Bomcode")
                {
                    Bommodel bomModel = view.GetRow(hitInfo.RowHandle) as Bommodel;
                    if (bomModel != null && _bomHasChildren.ContainsKey(bomModel.Bomcode) && _bomHasChildren[bomModel.Bomcode])
                    {
                        // 计算层级缩进
                        int level = 0;
                        if (!string.IsNullOrEmpty(bomModel.Bomranks))
                        {
                            int.TryParse(bomModel.Bomranks, out level);
                        }
                        
                        // 每个层级缩进30像素，与自定义绘制单元格方法保持一致
                        int indent = level * 30;
                        if (indent < 0) indent = 0;
                        
                        // 检查点击位置是否在+/-符号区域内
                        // 使用相对位置计算
                        int clickX = e.X - hitInfo.HitPoint.X;
                        
                        if (clickX >= indent && clickX <= indent + 20)
                        {
                            // 切换展开/收起状态
                            bomModel.IsExpanded = !bomModel.IsExpanded;
                            
                            // 根据展开状态加载或隐藏子项
                            if (bomModel.IsExpanded)
                            {
                                Console.WriteLine($"展开BOM节点: {bomModel.Bomcode}, ID: {bomModel.Id}");
                                LoadBomChildren(bomModel.Id);
                            }
                            else
                            {
                                Console.WriteLine($"收起BOM节点: {bomModel.Bomcode}, ID: {bomModel.Id}");
                                HideBomChildren(bomModel.Id);
                            }
                            
                            // 刷新视图
                            view.RefreshData();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"鼠标点击处理异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        /// <summary>
        /// 加载产品项数据到下拉框
        /// </summary>
        private void LoadProductItems()
        {
            try
            {
                // 清空下拉框
                textEdit1.Properties.Items.Clear();

                // 添加空选项
                textEdit1.Properties.Items.Add(" ");
                
                // 计数器，用于跟踪添加的成品数量
                int finishedProductCount = 0;
                
                // 只添加类型为"成品"的产品项
                foreach (var item in _bomTypeRankMapping)
                {
                    // 检查是否为成品类型
                    if (item.Value.Item1 == "成品")
                    {
                        textEdit1.Properties.Items.Add(item.Key);
                        finishedProductCount++;
                    }
                }
                
                // 如果没有成品，添加提示信息
                if (finishedProductCount == 0)
                {
                    XtraMessageBox.Show("未找到类型为\"成品\"的BOM项", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                
                // 设置默认选择第一项
                if (textEdit1.Properties.Items.Count > 0)
                {
                    textEdit1.SelectedIndex = 0;
                }
                
                // 设置提示文本
                textEdit1.Properties.NullText = "请选择成品BOM编码";
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载产品项数据异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 检查BOM是否有子项
        /// </summary>
        private async Task<bool> CheckBomHasChildren(long bomId)
        {
            try
            {
                // 构建API URL
                string url = $"api/Bom/GetBomDetailWithChildren?id={bomId}";
                
                Console.WriteLine($"检查BOM子项请求URL: {ApiBaseUrl}{url}");
                
                // 使用HttpClient调用API
                using (HttpClient client = new HttpClient())
                {
                    // 设置基础地址
                    client.BaseAddress = new Uri(ApiBaseUrl);
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送GET请求
                    HttpResponseMessage response = await client.GetAsync(url);
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API响应内容: {responseContent}");
                        
                        try
                        {
                            // 解析JSON响应
                            JObject jsonResponse = JObject.Parse(responseContent);
                            
                            // 检查是否有子集数据
                            // 首先检查是否有Code字段，确认API调用成功
                            string code = jsonResponse["Code"]?.ToString() ?? jsonResponse["code"]?.ToString();
                            if (code != "200")
                            {
                                return false;
                            }
                            
                            // 检查Data.Children字段
                            JArray childrenArray = null;
                            
                            // 尝试获取Children数组
                            if (jsonResponse["Data"] is JObject dataObj && dataObj["Children"] is JArray)
                            {
                                childrenArray = dataObj["Children"] as JArray;
                            }
                            else if (jsonResponse["data"] is JObject dataObj2 && dataObj2["Children"] is JArray)
                            {
                                childrenArray = dataObj2["Children"] as JArray;
                            }
                            else if (jsonResponse["Data"] is JObject dataObj3 && dataObj3["children"] is JArray)
                            {
                                childrenArray = dataObj3["children"] as JArray;
                            }
                            else if (jsonResponse["data"] is JObject dataObj4 && dataObj4["children"] is JArray)
                            {
                                childrenArray = dataObj4["children"] as JArray;
                            }
                            // 直接检查Data字段是否为数组
                            else if (jsonResponse["Data"] is JArray)
                            {
                                childrenArray = jsonResponse["Data"] as JArray;
                            }
                            else if (jsonResponse["data"] is JArray)
                            {
                                childrenArray = jsonResponse["data"] as JArray;
                            }
                            // 检查children字段
                            else if (jsonResponse["Children"] is JArray)
                            {
                                childrenArray = jsonResponse["Children"] as JArray;
                            }
                            else if (jsonResponse["children"] is JArray)
                            {
                                childrenArray = jsonResponse["children"] as JArray;
                            }
                            
                            // 如果找到了子项数组，检查是否有元素
                            if (childrenArray != null && childrenArray.Count > 0)
                            {
                                return true;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"解析JSON响应异常: {ex.Message}\n{ex.StackTrace}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"API请求失败，状态码: {response.StatusCode}");
                    }
                }
                
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"检查BOM子项异常: {ex.Message}\n{ex.StackTrace}");
                return false;
            }
        }
        
        /// <summary>
        /// 加载BOM子项
        /// </summary>
        private async void LoadBomChildren(long parentId)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                
                // 构建API URL
                string url = $"api/Bom/GetBomDetailWithChildren?id={parentId}";
                
                Console.WriteLine($"加载BOM子项请求URL: {ApiBaseUrl}{url}");
                
                // 获取当前数据源
                List<Bommodel> currentDataSource = GetCurrentDataSource();
                if (currentDataSource == null)
                {
                    currentDataSource = new List<Bommodel>();
                }
                
                // 找到父项在数据源中的索引
                int parentIndex = currentDataSource.FindIndex(b => b.Id == parentId);
                if (parentIndex < 0)
                {
                    Console.WriteLine($"未找到父项，ID: {parentId}");
                    return;
                }
                
                // 获取父项信息
                Bommodel parentBom = currentDataSource[parentIndex];
                int parentLevel = 0;
                if (!string.IsNullOrEmpty(parentBom.Bomranks))
                {
                    int.TryParse(parentBom.Bomranks, out parentLevel);
                }
                
                // 使用HttpClient调用API
                using (HttpClient client = new HttpClient())
                {
                    // 设置基础地址
                    client.BaseAddress = new Uri(ApiBaseUrl);
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送GET请求
                    HttpResponseMessage response = await client.GetAsync(url);
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API响应内容: {responseContent}");
                        
                        // 解析JSON响应
                        JObject jsonResponse = JObject.Parse(responseContent);
                        
                        // 检查响应状态码
                        string code = jsonResponse["Code"]?.ToString() ?? jsonResponse["code"]?.ToString();
                        if (code != "200")
                        {
                            XtraMessageBox.Show($"加载子项失败: {jsonResponse["Message"]?.ToString() ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        
                        // 获取子项数据
                        List<Bommodel> childrenList = new List<Bommodel>();
                        
                        // 尝试不同的字段名解析子项数据
                        JArray childrenArray = null;
                        
                        // 尝试获取Children数组
                        if (jsonResponse["Data"] is JObject dataObj && dataObj["Children"] is JArray)
                        {
                            childrenArray = dataObj["Children"] as JArray;
                        }
                        else if (jsonResponse["data"] is JObject dataObj2 && dataObj2["Children"] is JArray)
                        {
                            childrenArray = dataObj2["Children"] as JArray;
                        }
                        else if (jsonResponse["Data"] is JObject dataObj3 && dataObj3["children"] is JArray)
                        {
                            childrenArray = dataObj3["children"] as JArray;
                        }
                        else if (jsonResponse["data"] is JObject dataObj4 && dataObj4["children"] is JArray)
                        {
                            childrenArray = dataObj4["children"] as JArray;
                        }
                        // 直接检查Data字段是否为数组
                        else if (jsonResponse["Data"] is JArray)
                        {
                            childrenArray = jsonResponse["Data"] as JArray;
                        }
                        else if (jsonResponse["data"] is JArray)
                        {
                            childrenArray = jsonResponse["data"] as JArray;
                        }
                        // 检查children字段
                        else if (jsonResponse["Children"] is JArray)
                        {
                            childrenArray = jsonResponse["Children"] as JArray;
                        }
                        else if (jsonResponse["children"] is JArray)
                        {
                            childrenArray = jsonResponse["children"] as JArray;
                        }
                        
                        if (childrenArray != null && childrenArray.Count > 0)
                        {
                            // 尝试将数组转换为BOM模型列表
                            foreach (JObject item in childrenArray)
                            {
                                try
                                {
                                    Bommodel bomModel = item.ToObject<Bommodel>();
                                    if (bomModel != null)
                                    {
                                        // 设置为未展开状态
                                        bomModel.IsExpanded = false;
                                        
                                        // 确保子项的层级是父项层级+1
                                        bomModel.Bomranks = (parentLevel + 1).ToString();
                                        
                                        // 检查此子项是否也有子项
                                        bool hasChildren = await CheckBomHasChildren(bomModel.Id);
                                        _bomHasChildren[bomModel.Bomcode] = hasChildren;
                                        
                                        childrenList.Add(bomModel);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine($"解析子项异常: {ex.Message}");
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine("未找到子项数据");
                            XtraMessageBox.Show("未找到子项数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }
                        
                        // 如果成功获取到子项数据
                        if (childrenList.Count > 0)
                        {
                            // 在父项后插入子项
                            currentDataSource.InsertRange(parentIndex + 1, childrenList);
                            
                            // 更新数据源
                            gridControl1.DataSource = null;
                            gridControl1.DataSource = currentDataSource;
                            
                            // 刷新视图
                            gridView1.RefreshData();
                            
                            Console.WriteLine($"成功加载 {childrenList.Count} 个子项");
                        }
                        else
                        {
                            Console.WriteLine("未找到子项数据");
                            XtraMessageBox.Show("未找到子项数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        Console.WriteLine($"API请求失败，状态码: {response.StatusCode}");
                        XtraMessageBox.Show($"加载子项失败，HTTP状态码: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载BOM子项异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"加载BOM子项异常: {ex.Message}\n{ex.StackTrace}");
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 处理网格双击事件
        /// </summary>
        private void GridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (view == null) return;
                
                // 获取当前点击位置
                Point pt = Control.MousePosition;
                pt = view.GridControl.PointToClient(pt);
                
                // 获取点击的行信息
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = view.CalcHitInfo(pt);
                
                if (hitInfo.InRow)
                {
                    // 获取选中行的BOM对象
                    Bommodel bomModel = view.GetRow(hitInfo.RowHandle) as Bommodel;
                    if (bomModel != null && _bomHasChildren.ContainsKey(bomModel.Bomcode) && _bomHasChildren[bomModel.Bomcode])
                    {
                        // 如果双击的行有子项，则切换展开/收起状态
                        bomModel.IsExpanded = !bomModel.IsExpanded;
                        
                        // 根据展开状态加载或隐藏子项
                        if (bomModel.IsExpanded)
                        {
                            Console.WriteLine($"双击展开BOM节点: {bomModel.Bomcode}, ID: {bomModel.Id}");
                            LoadBomChildren(bomModel.Id);
                        }
                        else
                        {
                            Console.WriteLine($"双击收起BOM节点: {bomModel.Bomcode}, ID: {bomModel.Id}");
                            HideBomChildren(bomModel.Id);
                        }
                        
                        // 刷新视图
                        view.RefreshData();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"双击处理异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        /// <summary>
        /// 隐藏BOM子项
        /// </summary>
        private void HideBomChildren(long parentId)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                
                // 获取当前数据源
                List<Bommodel> currentDataSource = null;
                if (gridControl1.DataSource is List<Bommodel>)
                {
                    currentDataSource = gridControl1.DataSource as List<Bommodel>;
                }
                else
                {
                    // 如果数据源不是预期类型，创建一个新的列表
                    currentDataSource = new List<Bommodel>();
                    foreach (Bommodel item in gridControl1.DataSource as IEnumerable<Bommodel>)
                    {
                        currentDataSource.Add(item);
                    }
                }
                
                if (currentDataSource == null || currentDataSource.Count == 0)
                {
                    return;
                }
                
                // 找到父项在数据源中的索引
                int parentIndex = currentDataSource.FindIndex(b => b.Id == parentId);
                if (parentIndex >= 0)
                {
                    // 获取父项信息
                    Bommodel parentBom = currentDataSource[parentIndex];
                    
                    // 创建一个新的列表，只保留非子项
                    List<Bommodel> newDataSource = new List<Bommodel>();
                    
                    // 先添加父项之前的所有项
                    for (int i = 0; i <= parentIndex; i++)
                    {
                        newDataSource.Add(currentDataSource[i]);
                    }
                    
                    // 获取父项层级
                    int parentLevel = 0;
                    if (!string.IsNullOrEmpty(parentBom.Bomranks))
                    {
                        int.TryParse(parentBom.Bomranks, out parentLevel);
                    }
                    
                    // 从父项后一个开始遍历，跳过所有子项
                    bool foundNonChild = false;
                    for (int i = parentIndex + 1; i < currentDataSource.Count; i++)
                    {
                        int currentLevel = 0;
                        if (!string.IsNullOrEmpty(currentDataSource[i].Bomranks))
                        {
                            int.TryParse(currentDataSource[i].Bomranks, out currentLevel);
                        }
                        
                        // 如果层级小于等于父项层级，说明不是子项
                        if (currentLevel <= parentLevel)
                        {
                            foundNonChild = true;
                            newDataSource.Add(currentDataSource[i]);
                        }
                    }
                    
                    // 更新数据源
                    gridControl1.DataSource = null;
                    gridControl1.DataSource = newDataSource;
                    
                    // 刷新视图
                    gridView1.RefreshData();
                    
                    Console.WriteLine($"隐藏子项完成，移除了 {currentDataSource.Count - newDataSource.Count} 个子项");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"隐藏BOM子项异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"隐藏BOM子项异常: {ex.Message}\n{ex.StackTrace}");
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 加载BOM数据
        /// </summary>
        private async void LoadData(string bomCode = "")
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                
                // 构建API URL
                string url = $"api/Bom/GetBomsByCode";
                
                // 如果有编号参数，添加到URL
                if (!string.IsNullOrEmpty(bomCode))
                {
                    url += $"?bomCode={HttpUtility.UrlEncode(bomCode)}";
                }
                
                Console.WriteLine($"请求URL: {ApiBaseUrl}{url}");
                
                // 使用HttpClient调用API
                using (HttpClient client = new HttpClient())
                {
                    try
                    {
                        // 设置基础地址
                        client.BaseAddress = new Uri(ApiBaseUrl);
                        // 设置超时时间
                        client.Timeout = TimeSpan.FromSeconds(30);
                        
                        // 发送GET请求
                        HttpResponseMessage response = await client.GetAsync(url);
                        
                        // 检查响应状态
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();
                            Console.WriteLine($"API响应内容: {responseContent}");
                            
                            try
                            {
                                // 解析JSON响应
                                JObject jsonResponse = JObject.Parse(responseContent);
                                
                                // 检查响应状态码
                                string code = jsonResponse["Code"]?.ToString() ?? jsonResponse["code"]?.ToString();
                                if (code == "200")
                                {
                                    // 获取数据数组
                                    JArray dataArray = null;
                                    if (jsonResponse["Data"] != null && jsonResponse["Data"] is JArray)
                                    {
                                        dataArray = jsonResponse["Data"] as JArray;
                                    }
                                    else if (jsonResponse["data"] != null && jsonResponse["data"] is JArray)
                                    {
                                        dataArray = jsonResponse["data"] as JArray;
                                    }
                                    
                                    if (dataArray != null && dataArray.Count > 0)
                                    {
                                        // 反序列化为BOM模型列表
                                        List<Bommodel> bomList = new List<Bommodel>();
                                        foreach (JObject item in dataArray)
                                        {
                                            try
                                            {
                                                Bommodel bomModel = item.ToObject<Bommodel>();
                                                if (bomModel != null)
                                                {
                                                    bomList.Add(bomModel);
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine($"解析单个BOM项异常: {ex.Message}");
                                            }
                                        }
                                        
                                        // 检查每个BOM是否有子项并更新类型
                                        foreach (var bom in bomList)
                                        {
                                            bool hasChildren = await CheckBomHasChildren(bom.Id);
                                            _bomHasChildren[bom.Bomcode] = hasChildren;
                                            
                                            // 默认设置为未展开
                                            bom.IsExpanded = false;
                                            
                                            // 更新BOM类型和阶别
                                            var typeRank = GetBomTypeAndRankByCode(bom.Bomcode);
                                            bom.BomType = typeRank.Item1; // 使用映射的类型
                                        }
                                        
                                        // 绑定数据到GridControl
                                        gridControl1.DataSource = bomList;
                                        
                                        // 配置GridView选项
                                        ConfigureGridViewOptions();
                                        
                                        Console.WriteLine($"成功加载数据: {bomList.Count}条记录");
                                        return;
                                    }
                                    else
                                    {
                                        // 如果没有数据，尝试加载示例数据
                                        Console.WriteLine("API返回数据为空，加载示例数据");
                                        LoadExampleData(bomCode);
                                    }
                                }
                                else
                                {
                                    string message = jsonResponse["Message"]?.ToString() ?? 
                                                    jsonResponse["message"]?.ToString() ?? 
                                                    "API返回错误";
                                    XtraMessageBox.Show($"加载数据失败: {message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    
                                    // 加载示例数据
                                    LoadExampleData(bomCode);
                                }
                            }
                            catch (Exception jsonEx)
                            {
                                Console.WriteLine($"JSON解析异常: {jsonEx.Message}\n{jsonEx.StackTrace}");
                                XtraMessageBox.Show($"解析响应数据异常: {jsonEx.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                
                                // 加载示例数据
                                LoadExampleData(bomCode);
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show($"API请求失败，状态码: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            
                            // 加载示例数据
                            LoadExampleData(bomCode);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"API请求异常: {ex.Message}\n{ex.StackTrace}");
                        XtraMessageBox.Show($"API请求异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        
                        // 加载示例数据
                        LoadExampleData(bomCode);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载数据异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"加载数据异常: {ex.Message}\n{ex.StackTrace}");
                
                // 加载示例数据
                LoadExampleData(bomCode);
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 加载无人机BOM示例数据
        /// </summary>
        private async void LoadExampleData(string filterCode = "")
        {
            try
            {
                // 创建示例数据列表
                List<Bommodel> exampleData = new List<Bommodel>
                {
                    new Bommodel
                    {
                        Id = 1,
                        Bomcode = "UAV001",
                        Bomname = "无人机整机",
                        Bomversion = "1.0",
                        BomType = "成品",  // 使用正确的类型
                        Bomranks = "0",  // 阶别为0
                        Processmanagementcode = "P001",
                        Processmanagementname = "无人机组装",
                        Bomdosage = "1",
                        Bomdescription = "四旋翼无人机整机",
                        CreatedTime = DateTime.Now,
                        UpdatedTime = DateTime.Now,
                        CreatedBy = "system",
                        UpdatedBy = "system",
                        IsDeleted = false,
                        Productitemid = "UAV001",
                        IsExpanded = false
                    }
                };
                
                // 设置示例数据的子项关系
                _bomHasChildren["UAV001"] = true;  // 无人机整机有子项
                _bomHasChildren["UAV002"] = false;
                _bomHasChildren["UAV003"] = false;
                _bomHasChildren["UAV004"] = false;
                _bomHasChildren["UAV005"] = false;
                
                // 如果有筛选条件，则只显示匹配的数据
                if (!string.IsNullOrEmpty(filterCode))
                {
                    if (filterCode == "UAV001")
                    {
                        // 如果查询的是整机，则添加其子项
                        exampleData.AddRange(new List<Bommodel>
                        {
                            new Bommodel
                            {
                                Id = 2,
                                Bomcode = "UAV002",
                                Bomname = "无人机机身",
                                Bomversion = "1.0",
                                BomType = "半成品",  // 使用正确的类型
                                Bomranks = "1",  // 二级项，层级为1
                                Processmanagementcode = "P002",
                                Processmanagementname = "机身组装",
                                Bomdosage = "1",
                                Bomdescription = "无人机机身骨架",
                                CreatedTime = DateTime.Now,
                                UpdatedTime = DateTime.Now,
                                CreatedBy = "system",
                                UpdatedBy = "system",
                                IsDeleted = false,
                                Productitemid = "UAV002",
                                Parentid = 1,
                                IsExpanded = false
                            },
                            new Bommodel
                            {
                                Id = 3,
                                Bomcode = "UAV003",
                                Bomname = "无人机电机",
                                Bomversion = "1.0",
                                BomType = "原材料",  // 使用正确的类型
                                Bomranks = "1",  // 二级项，层级为1
                                Processmanagementcode = "P003",
                                Processmanagementname = "电机安装",
                                Bomdosage = "4",
                                Bomdescription = "四旋翼电机",
                                CreatedTime = DateTime.Now,
                                UpdatedTime = DateTime.Now,
                                CreatedBy = "system",
                                UpdatedBy = "system",
                                IsDeleted = false,
                                Productitemid = "UAV003",
                                Parentid = 1,
                                IsExpanded = false
                            },
                            new Bommodel
                            {
                                Id = 4,
                                Bomcode = "UAV004",
                                Bomname = "无人机螺旋桨",
                                Bomversion = "1.0",
                                BomType = "原材料",  // 使用正确的类型
                                Bomranks = "1",  // 二级项，层级为1
                                Processmanagementcode = "P004",
                                Processmanagementname = "螺旋桨安装",
                                Bomdosage = "4",
                                Bomdescription = "高强度复合材料螺旋桨",
                                CreatedTime = DateTime.Now,
                                UpdatedTime = DateTime.Now,
                                CreatedBy = "system",
                                UpdatedBy = "system",
                                IsDeleted = false,
                                Productitemid = "UAV004",
                                Parentid = 1,
                                IsExpanded = false
                            },
                            new Bommodel
                            {
                                Id = 5,
                                Bomcode = "UAV005",
                                Bomname = "无人机电池",
                                Bomversion = "1.0",
                                BomType = "原材料",  // 使用正确的类型
                                Bomranks = "1",  // 二级项，层级为1
                                Processmanagementcode = "P005",
                                Processmanagementname = "电池安装",
                                Bomdosage = "1",
                                Bomdescription = "高容量锂电池",
                                CreatedTime = DateTime.Now,
                                UpdatedTime = DateTime.Now,
                                CreatedBy = "system",
                                UpdatedBy = "system",
                                IsDeleted = false,
                                Productitemid = "UAV005",
                                Parentid = 1,
                                IsExpanded = false
                            }
                        });
                        
                        // 设置UAV001为展开状态
                        exampleData[0].IsExpanded = true;
                    }
                    else
                    {
                        // 如果查询的是其他编码，则只显示该项
                        exampleData = exampleData.Where(b => b.Bomcode == filterCode).ToList();
                        
                        // 如果没有找到匹配项，尝试在子项中查找
                        if (exampleData.Count == 0)
                        {
                            Bommodel childItem = null;
                            
                            // 根据编码获取类型和阶别
                            var typeRank = GetBomTypeAndRankByCode(filterCode);
                            string bomType = typeRank.Item1;
                            string bomRank = typeRank.Item2;
                            
                            switch (filterCode)
                            {
                                case "UAV002":
                                    childItem = new Bommodel
                                    {
                                        Id = 2,
                                        Bomcode = "UAV002",
                                        Bomname = "无人机机身",
                                        Bomversion = "1.0",
                                        BomType = bomType,  // 使用映射的类型
                                        Bomranks = bomRank,  // 使用映射的阶别
                                        Processmanagementcode = "P002",
                                        Processmanagementname = "机身组装",
                                        Bomdosage = "1",
                                        Bomdescription = "无人机机身骨架",
                                        CreatedTime = DateTime.Now,
                                        UpdatedTime = DateTime.Now,
                                        CreatedBy = "system",
                                        UpdatedBy = "system",
                                        IsDeleted = false,
                                        Productitemid = "UAV002",
                                        IsExpanded = false
                                    };
                                    break;
                                case "UAV003":
                                    childItem = new Bommodel
                                    {
                                        Id = 3,
                                        Bomcode = "UAV003",
                                        Bomname = "无人机电机",
                                        Bomversion = "1.0",
                                        BomType = bomType,  // 使用映射的类型
                                        Bomranks = bomRank,  // 使用映射的阶别
                                        Processmanagementcode = "P003",
                                        Processmanagementname = "电机安装",
                                        Bomdosage = "4",
                                        Bomdescription = "四旋翼电机",
                                        CreatedTime = DateTime.Now,
                                        UpdatedTime = DateTime.Now,
                                        CreatedBy = "system",
                                        UpdatedBy = "system",
                                        IsDeleted = false,
                                        Productitemid = "UAV003",
                                        IsExpanded = false
                                    };
                                    break;
                                case "UAV004":
                                    childItem = new Bommodel
                                    {
                                        Id = 4,
                                        Bomcode = "UAV004",
                                        Bomname = "无人机螺旋桨",
                                        Bomversion = "1.0",
                                        BomType = bomType,  // 使用映射的类型
                                        Bomranks = bomRank,  // 使用映射的阶别
                                        Processmanagementcode = "P004",
                                        Processmanagementname = "螺旋桨安装",
                                        Bomdosage = "4",
                                        Bomdescription = "高强度复合材料螺旋桨",
                                        CreatedTime = DateTime.Now,
                                        UpdatedTime = DateTime.Now,
                                        CreatedBy = "system",
                                        UpdatedBy = "system",
                                        IsDeleted = false,
                                        Productitemid = "UAV004",
                                        IsExpanded = false
                                    };
                                    break;
                                case "UAV005":
                                    childItem = new Bommodel
                                    {
                                        Id = 5,
                                        Bomcode = "UAV005",
                                        Bomname = "无人机电池",
                                        Bomversion = "1.0",
                                        BomType = bomType,  // 使用映射的类型
                                        Bomranks = bomRank,  // 使用映射的阶别
                                        Processmanagementcode = "P005",
                                        Processmanagementname = "电池安装",
                                        Bomdosage = "1",
                                        Bomdescription = "高容量锂电池",
                                        CreatedTime = DateTime.Now,
                                        UpdatedTime = DateTime.Now,
                                        CreatedBy = "system",
                                        UpdatedBy = "system",
                                        IsDeleted = false,
                                        Productitemid = "UAV005",
                                        IsExpanded = false
                                    };
                                    break;
                            }
                            
                            if (childItem != null)
                            {
                                exampleData.Add(childItem);
                            }
                        }
                    }
                }
                
                // 绑定数据到GridControl
                gridControl1.DataSource = exampleData;
                
                // 配置GridView选项
                ConfigureGridViewOptions();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载示例数据异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        /// <summary>
        /// 配置GridView选项
        /// </summary>
        private void ConfigureGridViewOptions()
        {
            try
            {
                // 设置各列属性
                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridView1.Columns)
                {
                    // 禁止列排序，以免影响树形结构显示
                    column.OptionsColumn.AllowSort = DevExpress.Utils.DefaultBoolean.False;

                    // 根据需要调整列宽
                    if (column.FieldName == "Bomcode")
                    {
                        column.Width = 220;
                    }
                    else if (column.FieldName == "Bomname")
                    {
                        column.Width = 150;
                    }
                    else if (column.FieldName == "添加下级")
                    {
                        // 为添加下级按钮添加自定义绘制事件
                        gridView1.CustomRowCellEdit += GridView1_CustomRowCellEdit;
                    }
                }
                
                // 设置列宽度，如果需要的话
                gridView1.BestFitColumns();
                
                // 刷新数据视图
                gridView1.RefreshData();
                
                Console.WriteLine("GridView配置完成");
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"配置网格选项异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"配置网格选项异常: {ex.Message}\n{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 自定义行单元格编辑器事件，用于控制添加下级按钮的可用性
        /// </summary>
        private void GridView1_CustomRowCellEdit(object sender, DevExpress.XtraGrid.Views.Grid.CustomRowCellEditEventArgs e)
        {
            try
            {
                if (e.Column.FieldName == "添加下级")
                {
                    // 获取当前行的BOM对象
                    Bommodel bomModel = gridView1.GetRow(e.RowHandle) as Bommodel;
                    if (bomModel != null)
                    {
                        // 根据BOM类型决定按钮是否可用
                        bool canAddChild = bomModel.BomType == "半成品" || bomModel.BomType == "成品";
                        
                        // 创建按钮编辑器
                        DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit buttonEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
                        buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
                        buttonEdit.Buttons[0].Caption = "添加下级";
                        buttonEdit.Buttons[0].Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph;
                        
                        // 设置按钮是否可用
                        buttonEdit.ReadOnly = !canAddChild;
                        
                        // 设置不同的外观
                        if (!canAddChild)
                        {
                            // 如果不可用，设置为灰色
                            buttonEdit.Buttons[0].Appearance.ForeColor = Color.Gray;
                            buttonEdit.Buttons[0].Appearance.Options.UseForeColor = true;
                            buttonEdit.Buttons[0].Enabled = false;
                        }
                        else
                        {
                            // 如果可用，设置为正常颜色
                            buttonEdit.Buttons[0].Appearance.ForeColor = Color.Black;
                            buttonEdit.Buttons[0].Appearance.Options.UseForeColor = true;
                            buttonEdit.Buttons[0].Enabled = true;
                        }
                        
                        // 应用编辑器
                        e.RepositoryItem = buttonEdit;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"自定义行单元格编辑器异常: {ex.Message}\n{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取BOM编码
                string bomCode = textEdit1.Text.Trim();
                
                // 如果选择了非空编码，验证是否为成品
                if (!string.IsNullOrWhiteSpace(bomCode))
                {
                    // 获取BOM类型
                    var typeRank = GetBomTypeAndRankByCode(bomCode);
                    if (typeRank.Item1 != "成品")
                    {
                        XtraMessageBox.Show("只能查询类型为\"成品\"的BOM", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                }
                
                Console.WriteLine($"执行查询: BOM编码=\"{bomCode}\"");
                
                // 调用加载数据方法
                LoadData(bomCode);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"查询操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 删除选中的BOM记录
        /// </summary>
        private async Task DeleteSelectedBom()
        {
            try
            {
                // 获取当前选中行的数据
                int rowHandle = gridView1.FocusedRowHandle;
                if (rowHandle < 0)
                {
                    XtraMessageBox.Show("请先选择要删除的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取选中行的BOM对象
                Bommodel selectedBom = gridView1.GetRow(rowHandle) as Bommodel;
                if (selectedBom == null)
                {
                    XtraMessageBox.Show("无法获取选中记录的数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 确认删除
                DialogResult result = XtraMessageBox.Show($"确定要删除编码为 {selectedBom.Bomcode} 的BOM记录吗？", "确认删除", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                
                if (result == DialogResult.No)
                {
                    return;
                }

                // 显示等待光标
                Cursor = Cursors.WaitCursor;

                // 构建API URL
                string url = $"api/Bom/SoftDeleteBom?id={selectedBom.Id}";
                
                Console.WriteLine($"请求URL: {ApiBaseUrl}{url}");
                
                // 使用HttpClient调用API
                using (HttpClient client = new HttpClient())
                {
                    // 设置基础地址
                    client.BaseAddress = new Uri(ApiBaseUrl);
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送PUT请求
                    HttpResponseMessage response = await client.PutAsync(url, null);
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string responseContent = await response.Content.ReadAsStringAsync();
                        
                        // 解析JSON响应
                        JObject jsonResponse = JObject.Parse(responseContent);
                        
                        // 检查响应状态码
                        string code = jsonResponse["Code"]?.ToString();
                        if (code == "200")
                        {
                            XtraMessageBox.Show("删除成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 重新加载数据
                            LoadData();
                        }
                        else
                        {
                            string message = jsonResponse["Message"]?.ToString() ?? "删除失败";
                            XtraMessageBox.Show($"删除失败: {message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        // 读取错误响应
                        string errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"删除失败，HTTP状态码: {response.StatusCode}\n{errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"删除操作异常: {ex.Message}\n{ex.StackTrace}");
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
        
        /// <summary>
        /// 行点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "删除")
            {
                DeleteSelectedBom();
            }
            else if(e.Column.FieldName == "添加下级")
            {
                // 获取当前选中行的BOM对象
                Bommodel selectedBom = gridView1.GetRow(e.RowHandle) as Bommodel;
                if (selectedBom != null)
                {
                    // 检查BOM类型是否允许添加下级
                    if (selectedBom.BomType != "成品" && selectedBom.BomType != "半成品")
                    {
                        return;
                    }
                    
                    AddChildBom();
                }
            }
            else if (e.Column.FieldName == "修改")
            {
                // 获取当前选中行的数据
                int rowHandle = gridView1.FocusedRowHandle;
                if (rowHandle < 0)
                {
                    XtraMessageBox.Show("请先选择要修改的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取选中行的BOM对象
                Bommodel selectedBom = gridView1.GetRow(rowHandle) as Bommodel;
                if (selectedBom == null)
                {
                    XtraMessageBox.Show("无法获取选中记录的数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 打开修改窗口
                BomUp bomUp = new BomUp(this, selectedBom);
                bomUp.ShowDialog();
            }
        }
        
        /// <summary>
        /// 添加下级BOM
        /// </summary>
        private void AddChildBom()
        {
            try
            {
                // 获取当前选中行的数据
                int rowHandle = gridView1.FocusedRowHandle;
                if (rowHandle < 0)
                {
                    XtraMessageBox.Show("请先选择要添加下级的记录", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 获取选中行的BOM对象
                Bommodel selectedBom = gridView1.GetRow(rowHandle) as Bommodel;
                if (selectedBom == null)
                {
                    XtraMessageBox.Show("无法获取选中记录的数据", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
                // 检查BOM类型是否允许添加下级
                if (selectedBom.BomType != "成品" && selectedBom.BomType != "半成品")
                {
                    XtraMessageBox.Show("只有成品或半成品可以添加下级", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 打开添加下级窗口，传递父BOM的ID
                OpenAddChildBomWindow(selectedBom.Id);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"添加下级操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"添加下级操作异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        /// <summary>
        /// 打开添加下级BOM窗口
        /// </summary>
        /// <param name="parentId">父BOM的ID</param>
        private void OpenAddChildBomWindow(long parentId)
        {
            try
            {
                // 创建一个新的BomUp实例，用于添加子BOM
                BomUp childBomUp = new BomUp(this);
                
                // 设置窗体标题
                childBomUp.Text = "添加下级BOM";
                
                // 设置父BOM ID的属性
                childBomUp.SetParentBomId(parentId);
                
                // 显示窗体
                childBomUp.ShowDialog();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"打开添加下级窗口异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"打开添加下级窗口异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        /// <summary>
        /// 刷新数据
        /// </summary>
        public void RefreshData()
        {
            try
            {
                // 重新加载数据
                LoadData();
                
                // 刷新视图
                gridView1.RefreshData();
                
                Console.WriteLine("数据刷新完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"刷新数据异常: {ex.Message}\n{ex.StackTrace}");
            }
        }
        
        /// <summary>
        /// 新增按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            BomUp bomUp = new BomUp(this);
            bomUp.ShowDialog();
        }
        /// <summary>
        /// 导出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button3_Click(object sender, EventArgs e)
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                
                // 构建API URL
                string url = "api/Bom/ExportBoms";
                
                Console.WriteLine($"导出请求URL: {ApiBaseUrl}{url}");
                
                // 使用HttpClient调用API
                using (HttpClient client = new HttpClient())
                {
                    // 设置基础地址
                    client.BaseAddress = new Uri(ApiBaseUrl);
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(60);
                    
                    // 发送GET请求
                    HttpResponseMessage response = await client.GetAsync(url);
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 获取文件名
                        string fileName = "BOM数据导出.xlsx";
                        if (response.Content.Headers.ContentDisposition != null)
                        {
                            fileName = response.Content.Headers.ContentDisposition.FileName;
                            // 移除可能的引号
                            fileName = fileName.Replace("\"", "");
                        }
                        
                        // 使用保存对话框让用户选择保存位置
                        SaveFileDialog saveFileDialog = new SaveFileDialog();
                        saveFileDialog.Filter = "Excel文件|*.xlsx";
                        saveFileDialog.Title = "保存BOM导出文件";
                        saveFileDialog.FileName = fileName;
                        
                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            // 读取响应内容为字节数组
                            byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
                            
                            // 保存文件
                            System.IO.File.WriteAllBytes(saveFileDialog.FileName, fileBytes);
                            
                            XtraMessageBox.Show("BOM数据导出成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        // 读取错误响应
                        string errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"导出失败，HTTP状态码: {response.StatusCode}\n{errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"导出操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"导出操作异常: {ex.Message}\n{ex.StackTrace}");
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// 展开全部
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button4_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                await ExpandAllNodes();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                XtraMessageBox.Show($"展开全部异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"展开全部异常: {ex.Message}\n{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 折叠全部
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                CollapseAllNodes();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                XtraMessageBox.Show($"折叠全部异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"折叠全部异常: {ex.Message}\n{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 展开所有节点
        /// </summary>
        private async Task ExpandAllNodes()
        {
            // 获取当前数据源
            List<Bommodel> currentDataSource = GetCurrentDataSource();
            if (currentDataSource == null || currentDataSource.Count == 0)
                return;

            // 记录需要展开的节点ID
            List<long> nodesToExpand = new List<long>();

            // 遍历所有节点，找出可展开的节点
            foreach (var bom in currentDataSource)
            {
                if (_bomHasChildren.ContainsKey(bom.Bomcode) && _bomHasChildren[bom.Bomcode] && !bom.IsExpanded)
                {
                    nodesToExpand.Add(bom.Id);
                }
            }

            // 展开所有需要展开的节点
            foreach (var nodeId in nodesToExpand)
            {
                await ExpandNodeAndChildren(nodeId);
            }

            // 刷新视图
            gridView1.RefreshData();
        }

        /// <summary>
        /// 递归展开节点及其子节点
        /// </summary>
        /// <param name="parentId">父节点ID</param>
        private async Task ExpandNodeAndChildren(long parentId)
        {
            // 获取当前数据源
            List<Bommodel> currentDataSource = GetCurrentDataSource();
            if (currentDataSource == null)
                return;

            // 找到父节点在数据源中的索引
            int parentIndex = currentDataSource.FindIndex(b => b.Id == parentId);
            if (parentIndex < 0)
                return;

            // 获取父节点
            Bommodel parentBom = currentDataSource[parentIndex];
            
            // 如果已经展开，则不需要再次展开
            if (parentBom.IsExpanded)
                return;

            // 设置为展开状态
            parentBom.IsExpanded = true;

            // 加载子节点
            await LoadNodeChildren(parentId);

            // 获取更新后的数据源
            currentDataSource = GetCurrentDataSource();
            if (currentDataSource == null)
                return;

            // 找到父节点在新数据源中的索引
            parentIndex = currentDataSource.FindIndex(b => b.Id == parentId);
            if (parentIndex < 0)
                return;

            // 获取父节点层级
            int parentLevel = 0;
            if (!string.IsNullOrEmpty(parentBom.Bomranks))
            {
                int.TryParse(parentBom.Bomranks, out parentLevel);
            }

            // 递归展开子节点
            for (int i = parentIndex + 1; i < currentDataSource.Count; i++)
            {
                int currentLevel = 0;
                if (!string.IsNullOrEmpty(currentDataSource[i].Bomranks))
                {
                    int.TryParse(currentDataSource[i].Bomranks, out currentLevel);
                }

                // 如果层级小于等于父节点层级，说明已经不是子节点了
                if (currentLevel <= parentLevel)
                    break;

                // 如果是直接子节点且有子项，则递归展开
                if (currentLevel == parentLevel + 1 && 
                    _bomHasChildren.ContainsKey(currentDataSource[i].Bomcode) && 
                    _bomHasChildren[currentDataSource[i].Bomcode])
                {
                    await ExpandNodeAndChildren(currentDataSource[i].Id);
                }
            }
        }

        /// <summary>
        /// 加载节点子项，与LoadBomChildren类似但返回Task
        /// </summary>
        private async Task LoadNodeChildren(long parentId)
        {
            // 获取当前数据源
            List<Bommodel> currentDataSource = GetCurrentDataSource();
            if (currentDataSource == null)
                return;

            // 找到父项在数据源中的索引
            int parentIndex = currentDataSource.FindIndex(b => b.Id == parentId);
            if (parentIndex < 0)
                return;

            // 获取父项信息
            Bommodel parentBom = currentDataSource[parentIndex];
            int parentLevel = 0;
            if (!string.IsNullOrEmpty(parentBom.Bomranks))
            {
                int.TryParse(parentBom.Bomranks, out parentLevel);
            }

            // 构建API URL
            string url = $"api/Bom/GetBomDetailWithChildren?id={parentId}";
            
            // 使用HttpClient调用API
            using (HttpClient client = new HttpClient())
            {
                // 设置基础地址
                client.BaseAddress = new Uri(ApiBaseUrl);
                // 设置超时时间
                client.Timeout = TimeSpan.FromSeconds(30);
                
                // 发送GET请求
                HttpResponseMessage response = await client.GetAsync(url);
                
                // 检查响应状态
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容
                    string responseContent = await response.Content.ReadAsStringAsync();
                    
                    // 解析JSON响应
                    JObject jsonResponse = JObject.Parse(responseContent);
                    
                    // 检查响应状态码
                    string code = jsonResponse["Code"]?.ToString() ?? jsonResponse["code"]?.ToString();
                    if (code != "200")
                    {
                        Console.WriteLine($"加载子项失败: {jsonResponse["Message"]?.ToString() ?? "未知错误"}");
                        return;
                    }
                    
                    // 获取子项数据
                    List<Bommodel> childrenList = new List<Bommodel>();
                    
                    // 尝试不同的字段名解析子项数据
                    JArray childrenArray = null;
                    
                    // 尝试获取Children数组
                    if (jsonResponse["Data"] is JObject dataObj && dataObj["Children"] is JArray)
                    {
                        childrenArray = dataObj["Children"] as JArray;
                    }
                    else if (jsonResponse["data"] is JObject dataObj2 && dataObj2["Children"] is JArray)
                    {
                        childrenArray = dataObj2["Children"] as JArray;
                    }
                    else if (jsonResponse["Data"] is JObject dataObj3 && dataObj3["children"] is JArray)
                    {
                        childrenArray = dataObj3["children"] as JArray;
                    }
                    else if (jsonResponse["data"] is JObject dataObj4 && dataObj4["children"] is JArray)
                    {
                        childrenArray = dataObj4["children"] as JArray;
                    }
                    // 直接检查Data字段是否为数组
                    else if (jsonResponse["Data"] is JArray)
                    {
                        childrenArray = jsonResponse["Data"] as JArray;
                    }
                    else if (jsonResponse["data"] is JArray)
                    {
                        childrenArray = jsonResponse["data"] as JArray;
                    }
                    // 检查children字段
                    else if (jsonResponse["Children"] is JArray)
                    {
                        childrenArray = jsonResponse["Children"] as JArray;
                    }
                    else if (jsonResponse["children"] is JArray)
                    {
                        childrenArray = jsonResponse["children"] as JArray;
                    }
                    
                    if (childrenArray != null && childrenArray.Count > 0)
                    {
                        // 尝试将数组转换为BOM模型列表
                        foreach (JObject item in childrenArray)
                        {
                            try
                            {
                                Bommodel bomModel = item.ToObject<Bommodel>();
                                if (bomModel != null)
                                {
                                    // 设置为未展开状态
                                    bomModel.IsExpanded = false;
                                    
                                    // 确保子项的层级是父项层级+1
                                    bomModel.Bomranks = (parentLevel + 1).ToString();
                                    
                                    // 检查此子项是否也有子项
                                    bool hasChildren = await CheckBomHasChildren(bomModel.Id);
                                    _bomHasChildren[bomModel.Bomcode] = hasChildren;
                                    
                                    childrenList.Add(bomModel);
                                }
                            }
                            catch
                            {
                                // 忽略解析异常
                            }
                        }
                    }
                    
                    // 如果成功获取到子项数据
                    if (childrenList.Count > 0)
                    {
                        // 获取最新的数据源
                        currentDataSource = GetCurrentDataSource();
                        if (currentDataSource == null)
                            return;

                        // 重新查找父项索引
                        parentIndex = currentDataSource.FindIndex(b => b.Id == parentId);
                        if (parentIndex < 0)
                            return;

                        // 在父项后插入子项
                        currentDataSource.InsertRange(parentIndex + 1, childrenList);
                        
                        // 更新数据源
                        gridControl1.DataSource = null;
                        gridControl1.DataSource = currentDataSource;
                        
                        Console.WriteLine($"成功加载 {childrenList.Count} 个子项");
                    }
                }
            }
        }

        /// <summary>
        /// 折叠所有节点
        /// </summary>
        private void CollapseAllNodes()
        {
            // 获取当前数据源
            List<Bommodel> currentDataSource = GetCurrentDataSource();
            if (currentDataSource == null || currentDataSource.Count == 0)
                return;

            // 创建一个新的列表，只保留顶级节点
            List<Bommodel> topLevelNodes = new List<Bommodel>();

            foreach (var bom in currentDataSource)
            {
                // 获取节点层级
                int level = 0;
                if (!string.IsNullOrEmpty(bom.Bomranks))
                {
                    int.TryParse(bom.Bomranks, out level);
                }

                // 只保留顶级节点（层级为0）
                if (level == 0)
                {
                    // 设置为未展开状态
                    bom.IsExpanded = false;
                    topLevelNodes.Add(bom);
                }
            }

            // 更新数据源
            gridControl1.DataSource = null;
            gridControl1.DataSource = topLevelNodes;

            // 刷新视图
            gridView1.RefreshData();
        }

        /// <summary>
        /// 获取当前数据源
        /// </summary>
        private List<Bommodel> GetCurrentDataSource()
        {
            if (gridControl1.DataSource == null)
                return new List<Bommodel>();

            if (gridControl1.DataSource is List<Bommodel> list)
            {
                return list;
            }
            else if (gridControl1.DataSource is IEnumerable<Bommodel> enumerable)
            {
                return enumerable.ToList();
            }

            return new List<Bommodel>();
        }
        /// <summary>
        /// 同步数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void button6_Click(object sender, EventArgs e)
        {
            try
            {
                // 显示等待光标
                Cursor = Cursors.WaitCursor;
                
                // 构建API URL
                string url = "api/Bom/SyncBomData";
                
                Console.WriteLine($"同步数据请求URL: {ApiBaseUrl}{url}");
                
                // 使用HttpClient调用API
                using (HttpClient client = new HttpClient())
                {
                    // 设置基础地址
                    client.BaseAddress = new Uri(ApiBaseUrl);
                    // 设置超时时间
                    client.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送GET请求
                    HttpResponseMessage response = await client.GetAsync(url);
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string responseContent = await response.Content.ReadAsStringAsync();
                        Console.WriteLine($"API响应内容: {responseContent}");
                        
                        // 解析JSON响应
                        JObject jsonResponse = JObject.Parse(responseContent);
                        
                        // 检查响应状态码
                        string code = jsonResponse["Code"]?.ToString() ?? jsonResponse["code"]?.ToString();
                        if (code == "200")
                        {
                            XtraMessageBox.Show("BOM数据同步成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            
                            // 刷新页面数据
                            RefreshData();
                        }
                        else
                        {
                            string message = jsonResponse["Message"]?.ToString() ?? 
                                            jsonResponse["message"]?.ToString() ?? 
                                            "同步失败";
                            XtraMessageBox.Show($"同步失败: {message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        // 读取错误响应
                        string errorContent = await response.Content.ReadAsStringAsync();
                        XtraMessageBox.Show($"同步失败，HTTP状态码: {response.StatusCode}\n{errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"同步操作异常: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Console.WriteLine($"同步操作异常: {ex.Message}\n{ex.StackTrace}");
            }
            finally
            {
                // 恢复光标
                Cursor = Cursors.Default;
            }
        }
    }
}